package com.chenyaowei.marketing.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.chenyaowei.common.exception.ServiceException;
import com.chenyaowei.common.utils.DateUtils;
import com.chenyaowei.marketing.domain.CywCouponHistory;
import com.chenyaowei.marketing.domain.CywCouponInfo;
import com.chenyaowei.marketing.enums.CouponGetTypeEnum;
import com.chenyaowei.marketing.enums.CouponUseStaticEnum;
import com.chenyaowei.marketing.mapper.CywCouponHistoryMapper;
import com.chenyaowei.marketing.request.CouponPickUpRequest;
import com.chenyaowei.marketing.service.ICywCouponHistoryService;
import com.chenyaowei.marketing.service.ICywCouponInfoService;
import com.chenyaowei.member.domain.CywIntegrationChangeHistory;
import com.chenyaowei.member.domain.CywMemberStatisticsInfo;
import com.chenyaowei.member.service.ICywIntegrationChangeHistoryService;
import com.chenyaowei.member.service.ICywMemberStatisticsInfoService;
import com.chenyaowei.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

import static com.chenyaowei.common.utils.SecurityUtils.getUserId;

/**
 * 优惠券领取历史记录Service业务层处理
 *
 * @author 陈耀威
 * @date 2023-11-28
 */
@Service
public class CywCouponHistoryServiceImpl implements ICywCouponHistoryService
{
    @Autowired
    private CywCouponHistoryMapper cywCouponHistoryMapper;

    @Autowired
    private ICywCouponInfoService couponInfoService;

    @Autowired
    private ICywMemberStatisticsInfoService memberStatisticsInfoService;

    @Autowired
    private ICywIntegrationChangeHistoryService integrationChangeHistoryService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询优惠券领取历史记录
     *
     * @param id 优惠券领取历史记录主键
     * @return 优惠券领取历史记录
     */
    @Override
    public CywCouponHistory selectCywCouponHistoryById(Long id)
    {
        return cywCouponHistoryMapper.selectCywCouponHistoryById(id);
    }

    /**
     * 查询优惠券领取历史记录列表
     *
     * @param cywCouponHistory 优惠券领取历史记录
     * @return 优惠券领取历史记录
     */
    @Override
    public List<CywCouponHistory> selectCywCouponHistoryList(CywCouponHistory cywCouponHistory)
    {
        List<CywCouponHistory> list = cywCouponHistoryMapper.selectCywCouponHistoryList(cywCouponHistory);
        return list;
    }

    /**
     * 新增优惠券领取历史记录
     *
     * @param cywCouponHistory 优惠券领取历史记录
     * @return 结果
     */
    @Override
    public int insertCywCouponHistory(CywCouponHistory cywCouponHistory)
    {
        cywCouponHistory.setCreateTime(DateUtils.getNowDate());
        return cywCouponHistoryMapper.insertCywCouponHistory(cywCouponHistory);
    }

    /**
     * 修改优惠券领取历史记录
     *
     * @param cywCouponHistory 优惠券领取历史记录
     * @return 结果
     */
    @Override
    public int updateCywCouponHistory(CywCouponHistory cywCouponHistory)
    {
        return cywCouponHistoryMapper.updateCywCouponHistory(cywCouponHistory);
    }

    /**
     * 批量删除优惠券领取历史记录
     *
     * @param ids 需要删除的优惠券领取历史记录主键
     * @return 结果
     */
    @Override
    public int deleteCywCouponHistoryByIds(Long[] ids)
    {
        return cywCouponHistoryMapper.deleteCywCouponHistoryByIds(ids);
    }

    /**
     * 删除优惠券领取历史记录信息
     *
     * @param id 优惠券领取历史记录主键
     * @return 结果
     */
    @Override
    public int deleteCywCouponHistoryById(Long id)
    {
        return cywCouponHistoryMapper.deleteCywCouponHistoryById(id);
    }

    @Override
    public List<CywCouponHistory> selectListByUserId(Long userId) {
        return cywCouponHistoryMapper.selectListByUserId(userId);
    }

    @Override
    public List<CywCouponHistory> selectUseableCouponList(Long userId) {
        return cywCouponHistoryMapper.selectUseableCouponList(userId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int couponPickUp(CouponPickUpRequest couponClaimRequest) {
        Long couponId = couponClaimRequest.getCouponId();
        Long userId = getUserId();
        // 优惠卷信息
        CywCouponInfo couponInfo = couponInfoService.selectCywCouponInfoById(couponId);
        // 会员信息
        CywMemberStatisticsInfo memberStatisticsInfo = memberStatisticsInfoService.selectInfoByMemberId(userId);
        // 时间、令牌、积分够不够、还有没有、限领数量
        CywCouponHistory couponHistory = couponPickUpValidated(couponClaimRequest, couponInfo, memberStatisticsInfo);
        // 更新优惠券领取数量
        int count = couponInfoService.subtractCouponNum(couponInfo.getId());
        if (count == 0){
            throw new ServiceException("优惠券已领完");
        }
        couponHistory.setMemberNickName(userService.selectUserById(userId).getNickName());
        couponHistory.setGetType(CouponGetTypeEnum.ACTIVE.getCode());
        couponHistory.setCreateTime(new Date());
        couponHistory.setUseStatus(CouponUseStaticEnum.UN_USE.getCode());
        couponHistory.setUseTime(couponInfo.getEnableStartTime());
        couponHistory.setEndTime(couponInfo.getEnableEndTime());
        couponHistory.setCouponImg(couponInfo.getCouponImg());
        couponHistory.setCouponId(couponId);
        couponHistory.setUseType(couponInfo.getUseType());

        Integer requiredIntegral = couponInfo.getRequiredIntegral();
        if (requiredIntegral > 0) {
            // 积分记录
            Date date = new Date();
            CywIntegrationChangeHistory integrationChangeHistory = new CywIntegrationChangeHistory();
            integrationChangeHistory.setMemberId(userId);
            integrationChangeHistory.setCreateTime(date);
            integrationChangeHistory.setChangeCount(-requiredIntegral);
            integrationChangeHistory.setNote("兑换优惠卷");
            integrationChangeHistoryService.insertCywIntegrationChangeHistory(integrationChangeHistory);
        }

        memberStatisticsInfoService.updateCouponCount(userId, 1, -requiredIntegral);
        return cywCouponHistoryMapper.insertCywCouponHistory(couponHistory);

    }

    private CywCouponHistory couponPickUpValidated(CouponPickUpRequest request, CywCouponInfo couponInfo , CywMemberStatisticsInfo memberStatisticsInfo){
        if (!couponInfo.getCode().equals(request.getCode()) ||
                DateUtils.getNowDate().before(couponInfo.getStartTime()) ||
                DateUtils.getNowDate().after(couponInfo.getEndTime()) ||
                couponInfo.getNum() == 0 ||
                couponInfo.getMemberLevel() > memberStatisticsInfo.getMemberLevel() ||
                couponInfo.getRequiredIntegral() > memberStatisticsInfo.getIntegration()){
            throw new ServiceException("非法操作");
        }
        Integer perLimit = couponInfo.getPerLimit();
        CywCouponHistory couponHistory = new CywCouponHistory();
        couponHistory.setMemberId(getUserId());
        couponHistory.setCouponId(couponInfo.getId());
        List<CywCouponHistory> couponHistories = cywCouponHistoryMapper.selectCywCouponHistoryList(couponHistory);
        if (CollectionUtil.isNotEmpty(couponHistories)){
            if (couponHistories.size() == perLimit){
                throw new ServiceException("您领取的优惠券已达上限");
            }
        }
        return couponHistory;
    }
}
